package com.acane.instagram.mapper;

import com.acane.instagram.pojo.dto.CommentDTO;
import com.acane.instagram.pojo.dto.CommentLikeDTO;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.time.LocalDate;
import java.util.List;

@Mapper
public interface CommentMapper extends BaseMapper<CommentDTO> {

    @Select("select c.* from comments c left join post p on c.post_id = p.id " +
            "where p.user_id = #{userId} order by c.timestamp desc")
    List<CommentDTO> getCommentHistory(@Param("userId") String userId);

    @Select("select c.* from comments c left join post p on c.post_id = p.id ")
    List<CommentDTO> getCommentList(@Param("postId") String postId);

    @Update("UPDATE comments SET likes = likes + 1 WHERE id = #{commentId}")
    int likeComment(@Param("commentId") String commentId);

    @Update("UPDATE comments SET likes = likes - 1 WHERE id = #{commentId}")
    int unlikeComment(@Param("commentId") String commentId);


    @Select("select cl.* from comment_likes cl left join comments c on cl.comment_id = c.id " +
            "where c.commenter_id = #{userId} order by cl.timestamp desc")
    List<CommentLikeDTO> getCommentLikeHistory(@Param("userId") String userId);


    @Select("select * from comment_likes where comment_id = #{commentId} and liker_id = #{likerId}")
    CommentLikeDTO judgeIfAlreadyLike(@Param("commentId") String commentId, @Param("likerId") String likerId);

    @Select("SELECT COUNT(*) FROM comments WHERE post_id = #{postId}")
    int countByPostId(@Param("postId") String postId);

    @Select({
            "<script>",
            "SELECT c.* FROM comments c",
            "INNER JOIN user u ON c.commenter_id = u.id",
            "WHERE 1=1",
            "<if test='commenterUserName != null and commenterUserName != \"\"'>",
            "   AND u.user_name = #{commenterUserName}",
            "</if>",
            "<if test='content != null and content != \"\"'>",
            "   AND c.content LIKE CONCAT('%', #{content}, '%')",
            "</if>",
            "<if test='startDate != null'>",
            "   AND c.timestamp &gt;= #{startDate}",
            "</if>",
            "<if test='endDate != null'>",
            "   AND c.timestamp &lt;= #{endDate}",
            "</if>",
            "ORDER BY c.timestamp DESC",
            "LIMIT #{size} OFFSET #{offset}",
            "</script>"
    })
    List<CommentDTO> getAllComment(
            @Param("commenterUserName") String commenterUserName,
            @Param("content") String content,
            @Param("startDate") LocalDate startDate,
            @Param("endDate") LocalDate endDate,
            @Param("offset") Integer offset,
            @Param("size") Integer size
    );
}
